class Solution {
    public int maxSubarrayLength(int[] nums, int k) {
        int ans = 0;
        Map<Integer,Integer> cnt = new HashMap<>();
        int left = 0;
        for (int i = 0; i < nums.length; i++) {
            cnt.put(nums[i],cnt.getOrDefault(nums[i],0) + 1);
            if (cnt.containsKey(nums[i]) && cnt.get(nums[i]) > k) {
                while (nums[left] != nums[i]) {
                    cnt.put(nums[left],cnt.get(nums[left]) - 1);
                    if(cnt.get(nums[left]) == 0)cnt.remove(nums[left]);
                    left += 1;
                }
                cnt.put(nums[left],cnt.get(nums[left]) - 1);
                if(cnt.get(nums[left]) == 0)cnt.remove(nums[left]);
                left += 1;
            }
            ans = Math.max(ans,i - left + 1);
        }return ans;
    }
}